package main

import (
	"flag"
	"fmt"

	//	"github.com/hprose/hprose-go"

	"log"
	"sync"
	"time"

	hprose "github.com/hprose/hprose-golang/rpc"
)

var (
	Num  int
	Conn int
	Addr string
)

type EchoRequest struct {
	S string `simple:"true"`
}

type EchoRespone struct {
	Res int64 `simple:"true"`
}

type Stub struct {
	Echo func(*EchoRequest) (*EchoRespone, error) `simple:"true"`
}

const RS = 100000

func init() {
	flag.IntVar(&Num, "num", 5, "")
	flag.IntVar(&Conn, "conn", 5, "")
	flag.StringVar(&Addr, "addr", "127.0.0.1", "")
	flag.Parse()
}

func main() {
	clients := make([]*Stub, 0, 10)
	for i := 0; i < Conn; i++ {
		URI := "tcp" + "://" + Addr + ":" + "8000"
		client := hprose.NewClient(URI)
		stub := &Stub{}
		client.UseService(stub)
		clients = append(clients, stub)
	}
	index := 0
	s1 := EchoRequest{
		S: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
	}
	var wg sync.WaitGroup

	start := time.Now()

	for i := 0; i < Num; i++ {
		wg.Add(1)

		var c *Stub
		if index < len(clients) {
			c = clients[index]
			index++
		} else {
			index = 0
			c = clients[index]
		}

		go func(cli *Stub) {
			defer wg.Done()

			log.Println("goroutine start...")
			st := time.Now()

			for n := 0; n < RS; n++ {
				if _, err := cli.Echo(&s1); err != nil {
					log.Println(err)
				}
			}

			log.Println(time.Now().Sub(st))
		}(c)
	}
	wg.Wait()

	total := RS * Num
	secs := time.Now().Sub(start) / 1000000000

	fmt.Printf("concurrency: %d\n", Num)
	fmt.Printf("total: %d\n", total)
	fmt.Printf("seconds: %d\n", secs)
	fmt.Printf("qps: %d\n", total/int(secs))
}
